<!-- equipmentLedger -->
<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag" :class="isCloseTree ? 'tag-nav-close' : ''">
        <div class="main-nav">
          <div class="search-box">
            <a-button class="btns-item" size="small" @click="expandAll(true)">
              <Icon icon="ant-design:merge-cells-outlined" />
            </a-button>
            <a-button class="btns-item" size="small" @click="expandAll(false)">
              <Icon icon="ant-design:split-cells-outlined" />
            </a-button>
            <a-input-search
              v-model:value="searchDriver"
              placeholder="搜索"
              :allowClear="true"
              @search="onSearchDriver"
            />
          </div>
          <BasicTree
            title=""
            ref="treeRef"
            :treeData="treeDataPro"
            :fieldNames="{ key: 'Key', title: 'Name', children: 'Children' }"
            :onSelect="handleTreeSelect"
          />
        </div>
        <div class="main-sidebar" @click="handleSideBarClick">
          <div class="close-btn">
            <Icon
              :icon="
                isCloseTree ? 'ant-design:caret-right-filled' : 'ant-design:caret-left-outlined'
              "
            />
          </div>
        </div>
        <div class="main-content">
          <div class="form-box">
            <BasicForm @register="registerForm" v-show="enterpriseInfo.Key" />
          </div>
          <BasicTable
            @register="registerTable"
            :columns="columns"
            :dataSource="tableData"
            :canResize="false"
            :showIndexColumn="false"
            :striped="true"
            :bordered="true"
            :pagination="false"
            :actionColumn="hasPermission(['6-2-detail']) ? actionColumn : undefined"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'RunState'">
                <span :style="`color:${RunStateConfig[record.RunState].color}`">{{
                  RunStateConfig[record.RunState].txt
                }}</span>
              </template>
              <template v-if="column.key === 'ConnectState'">
                <span :style="`color:${ConnectStateConfig[record.ConnectState].color}`">{{
                  ConnectStateConfig[record.ConnectState].txt
                }}</span>
              </template>
              <template v-if="column.key === 'value'">
                <span style="color: blue">{{ record.value }}</span>
              </template>
              <template v-if="column.key === 'action' && hasPermission(['6-2-detail'])">
                <TableAction
                  :actions="[
                    {
                      label: '详情',
                      icon: 'ant-design:eye-filled',
                      ifShow: hasPermission('6-2-detail'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleShowDetail(record);
                      },
                    },
                  ]"
                />
              </template>
            </template>
            <template #toolbar v-if="enterpriseInfo.Key">
              <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
              <a-button class="btn-box-item" type="primary" @click="throttleSubmit">查询</a-button>
              <a-button type="primary" v-if="hasPermission('6-2-import')" @click="handleShowDetail">
                导出
              </a-button>
            </template>
          </BasicTable>
        </div>
        <div class="flex py-2 items-center justify-end pagination-box">
          <a-pagination
            :show-total="(total) => `共 ${total} 条数据`"
            showSizeChanger
            size="small"
            :current="paginationInfo.data.current"
            :pageSize="paginationInfo.data.pageSize"
            :total="paginationInfo.data.total"
            @change="handlePageChange"
          />
        </div>
      </div>
    </div>
    <!-- 详情的弹窗 -->
    <modelByDetail :info="detailForm" @register="registerByDetail" />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted, reactive, unref, nextTick } from 'vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useModal } from '/@/components/Modal';
  import dayjs from 'dayjs';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { Icon } from '/@/components/Icon';
  // import { cloneDeep } from 'lodash-es';
  import { Pagination } from 'ant-design-vue';
  import { getenterprisetree } from '/@/api/enterprise/index';
  import modelByDetail from '/@/views/project/equipmentStatus/components/modelByDetail.vue';
  import { BasicTree, TreeActionType } from '/@/components/Tree/index';
  import { getequipmentstate } from '/@/api/equipmentLedger/index';
  import { getdevicetypes } from '/@/api/equipmentType/index';
  import { getdevicemodels } from '/@/api/equipmentModel/index';
  import { useDebounceFn } from '@vueuse/core';

  const APagination = Pagination;
  let searchDriver = ref('');
  let treeDataPro = ref([]);
  let loading = ref(false);
  let tableData = reactive([]);
  let RunStateConfig = {
    0: {
      color: '',
      txt: '',
    },
    1: {
      color: '#5ec14a',
      txt: '运行',
    },
    2: {
      color: '#edb263',
      txt: '暂停',
    },
    3: {
      color: 'red',
      txt: '故障',
    },
    4: {
      color: '#6bbff0',
      txt: '停机',
    },
    5: {
      color: '#d9f79d',
      txt: '待机',
    },
    6: {
      color: '#89d6b0',
      txt: '调机',
    },
    7: {
      color: '#000000',
      txt: '离线',
    },
  };
  let ConnectStateConfig = {
    0: {
      color: '#000',
      txt: '未物联',
    },
    1: {
      color: 'green',
      txt: '在线',
    },
    2: {
      color: 'red',
      txt: '离线',
    },
  };
  // 设备类型
  let deviceTypeList = [];
  // 设备型号
  let deviceModelList = [];
  // 设备类别
  let CategoryObj = {
    1: '生产设备',
    2: '检测设备',
    3: '辅助设备',
    4: '厂务设备',
    5: '仪器仪表',
    6: '办公设备',
    7: ' IT设备',
    8: '其它',
  };
  let isCloseTree = ref(false);
  // 企业信息
  let enterpriseInfo = {};
  // let treeClickCount = 0;
  let detailForm = ref({});
  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  const treeRef = ref<Nullable<TreeActionType>>(null);
  const { hasPermission } = usePermission();

  const [registerByDetail, { openModal: openModalByDetail }] = useModal();
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'SearchCategory',
      component: 'Select',
      label: '设备类别：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [
          { label: '全部', value: 0 },
          { label: '生产设备', value: 1 },
          { label: '检测设备', value: 2 },
          { label: '辅助设备', value: 3 },
          { label: '厂务设备', value: 4 },
          { label: '仪器仪表', value: 5 },
          { label: '办公设备', value: 6 },
          { label: 'IT设备', value: 7 },
          { label: '其它', value: 8 },
        ],
      },
    },
    {
      field: 'searchTypeName',
      component: 'Select',
      label: '设备类型：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'TypeName', value: 'Id', key: 'Id' },
      },
    },
    {
      field: 'SearchModelCode',
      component: 'Select',
      label: '设备型号：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'ModelName', value: 'ModelCode', key: 'ModelCode' },
      },
    },
    {
      field: 'SearchCode',
      component: 'Input',
      label: '设备编码：',
      colProps: {
        span: 6,
      },
    },
  ];
  const [registerForm, { validateFields, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });

  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '设备编码',
      dataIndex: 'Code',
    },
    {
      title: '设备名称',
      dataIndex: 'Name',
    },
    {
      title: '运行状态',
      dataIndex: 'RunState',
    },
    {
      title: '链接状态',
      dataIndex: 'ConnectState',
    },

    {
      title: '更新时间',
      dataIndex: 'UpdateTime',
    },

    {
      title: '变量',
      dataIndex: 'TagFullName',
    },
    {
      title: '实时值',
      dataIndex: 'Value',
    },
    {
      title: '设备型号',
      dataIndex: 'Model_text',
    },
    {
      title: '设备类型',
      dataIndex: 'TypeName',
    },
    {
      title: '设备类别',
      dataIndex: 'Category_text',
    },
    {
      title: '工厂',
      dataIndex: 'Factory',
    },
    {
      title: '车间部门',
      dataIndex: 'Workshop',
    },

    {
      title: '产线',
      dataIndex: 'ProductionLine',
    },
  ];
  // 操作栏
  let actionColumn = {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };
  const [registerTable] = useTable();
  // 重置按钮点击事件
  async function handleResetFields() {
    setFieldsValue({
      SearchTypeName: '',
      SearchCode: '',
      SearchModelCode: '',
      SearchCategory: 0,
    });
    paginationInfo.data.current = 1;
  }
  // 查询按钮点击事件
  async function handleSubmit() {
    try {
      let res = await validateFields();
      getTableData(res);
    } catch {}
  }
  // 折叠左侧区域
  function handleSideBarClick() {
    isCloseTree.value = !isCloseTree.value;
  }
  // 展开 折叠
  function expandAll(checkAll) {
    getTree().expandAll(checkAll);
  }
  // 获取设备类型
  async function getDeviceTypes() {
    try {
      loading.value = true;

      let res = await getdevicetypes([
        {
          PageNO: 1,
          SearchTypeName: '',
          SearchCategory: 0,
          PageSize: 1000,
        },
      ]);

      deviceTypeList = res.Rows.map((item) => {
        item.CategoryCn = CategoryObj[item.Category];
        return item;
      });
      updateSchema({
        field: 'searchTypeName',
        componentProps: {
          options: deviceTypeList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取设备型号
  async function getDeviceModels() {
    try {
      loading.value = true;

      let res = await getdevicemodels([
        {
          PageNO: 1,
          searchModel: '',
          searchModelName: '',
          searchTypeName: '',
          searchTypeCategory: 0,
          PageSize: 1000,
        },
      ]);

      deviceModelList = res.Rows;
      updateSchema({
        field: 'SearchModelCode',
        componentProps: {
          options: deviceModelList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取树数据
  async function initData(isOpenTree = false) {
    loading.value = true;
    let resByTree = await getenterprisetree(searchDriver.value ? [true,searchDriver.value] : [true,null]);
    treeDataPro.value = resByTree || [];
    if (isOpenTree) {
      nextTick(() => {
        getTree().filterByLevel(1);
      });
    }

    loading.value = false;
  }
  // 获取树dom
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  // 重置搜索条件
  function initSearch() {
    setFieldsValue({
      SearchTypeName: '',
      SearchCode: '',
      SearchModelCode: '',
      SearchCategory: 0,
    });
    paginationInfo.data.current = 1;
  }
  // 树点击事件
  function handleTreeSelect(_e, info) {
    let val = info.node || {};
    enterpriseInfo = val;
    initSearch();
    getTableData();
    // treeClickCount++;

    // //单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
    // if (treeClickCount >= 2) {
    //   return;
    // }
    // //计时器,计算300毫秒为单位,可自行修改
    // setTimeout(() => {
    //   if (treeClickCount == 1) {
    //     //把次数归零
    //     treeClickCount = 0;
    //     // 单击事件
    //     // handleClickByTree(info);
    //   } else if (treeClickCount > 1) {
    //     //把次数归零
    //     treeClickCount = 0;
    //     //双击事件
    //     handleDbClickByTree(info);
    //   }
    // }, 300);
  }
  // 双击事件
  // function handleDbClickByTree(info) {
  //   let val = info.node || {};
  //   console.log(`output->val`, val);
  // }

  // 搜索树
  function onSearchDriver() {
    initData();
  }
  // 分页事件
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    getTableData();
  }
  // 详情
  function handleShowDetail(params) {
    detailForm.value = params;
    openModalByDetail();
  }

  // 获取设备集合
  async function getTableData(params = {}) {
    try {
      loading.value = true;
      let res = await getequipmentstate([
        {
          SearchCode: '',
          SearchModelCode: '',
          searchTypeName: '',
          SearchCategory: 0,
          SearchEnterpriseId: enterpriseInfo.Key,
          PageNO: paginationInfo.data.current,
          PageSize: paginationInfo.data.pageSize,
          ...params,
        },
      ]);
      paginationInfo.data.total = res.TotalRows;
      tableData = res.Rows.map((item) => {
        item.UpdateTIme = item.UpdateTIme && dayjs(item.UpdateTIme).format('YYYY-MM-DD HH:mm:ss');
        return item;
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  onMounted(async () => {
    initData(true);
    getDeviceTypes();
    getDeviceModels();
    // getTableData();
  });
</script>
<script lang="ts">
  export default {
    name: 'EquipmentLedgerIndexPage',
  };
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .search-box {
        display: flex;
        align-items: center;

        > .ant-btn-sm {
          height: 32px;
        }
      }

      .main-nav {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        width: 240px;
        height: calc(100%);
        padding: 8px;
        box-sizing: border-box;
        overflow: auto;
        border-right: 1px solid #ccc;

        ::v-deep(.vben-tree__title) {
          user-select: none !important;
        }
      }

      .main-sidebar {
        position: absolute;
        top: 0;
        left: 240px;
        bottom: 0;
        width: 12px;
        border-radius: 5px;
        cursor: pointer;
        user-select: none;

        .close-btn {
          position: absolute;
          top: 50%;
          left: 0;
          width: 12px;
          height: 30px;
          margin-top: -50%;

          line-height: 30px;
          text-align: center;
          background: #7dcdfe;
          border-radius: 6px;
          color: #fff;

          > span {
            font-size: 12px !important;
          }
        }
      }

      .main-sidebar:hover {
        background-color: #e2e3e5;
      }

      .main-content {
        position: relative;
        height: 100%;
        margin-left: 260px;
        overflow: hidden;

        .pagination-box {
          z-index: 9;
          padding: 10px 5px;
          box-sizing: border-box;
          position: absolute;
          width: 100%;
          bottom: 0;
          left: 0;
          right: 0;
          background-color: #fff;
        }
      }

      .main-content::after {
        content: '';
        display: block;
        width: 100%;
        height: 45px;
      }
    }

    .tag-nav-close {
      .main-nav {
        left: -260px;
      }

      .main-sidebar {
        left: 0;
      }

      .main-content {
        margin-left: 20px;
      }
    }
  }

  .form-box {
    padding: 5px;

    ::v-deep(.ant-form-item) {
      margin: 0 5px;
      margin-bottom: 8px;
    }
  }
</style>
